<template>
  <div
    class="addForm"
    @click="isCloseSelectBox"
  >
    <a-card
      v-if="curStep===0"
      :head-style="{'font-weight':'bold'}"
    >
      <div
        slot="title"
        style="display: flex;justify-content: space-between"
      >
        <div v-if="state==='add'">制定食谱</div>
        <div v-if="state==='edit'">修改食谱</div>
        <div v-if="state==='detail'">食谱详情</div>
        <a-button
          type="primary"
          @click="$emit('change-to-table')"
        >返回</a-button>
      </div>
      <a-card :head-style="{'background-color':'#f5f5f5'}">
        <template
          slot="title"
          class="ant-card-actions"
        >
          <a-form-model
            :model="form"
            layout="inline"
            @submit.native.prevent
          >
            <a-form-model-item label="食谱开始日期:">
              <a-date-picker
                v-model="form.starTime"
                :disabled="state==='detail'"
                @change="handleDateChange"
              />
            </a-form-model-item>
            <a-form-model-item label="食谱周期:">
              {{ form.planRange }}
            </a-form-model-item>
            <a-form-model-item
              :disabled="state==='detail'"
              label="计划食谱名称:"
            >
              <a-input
                v-model="form.planName"
                :disabled="state==='detail'"
              />
            </a-form-model-item>
          </a-form-model>
        </template>
        <a-modal
          v-model="showConfirmSelectDateDialog"
          :footer="null"
          class="confirmDateDialog"
          style="text-align: center"
          title="提示"
        >
          <div>
            <a-icon
              style="color: red;font-size: 15px"
              theme="filled"
              type="warning"
            />
            确认将{{ firstDayNameOfWeek }}设为本周开始日期？
          </div>
          <div>
            <a-button
              class="btn"
              @click="showConfirmSelectDateDialog=false"
            >修改日期</a-button>
            <a-button
              class="btn"
              @click="afterWeekChecked=[],showConfirmSelectDateDialog=false"
            >确定</a-button>
          </div>
        </a-modal>
        <table
          v-if="afterWeek.length!==0"
          class="table"
        >
          <caption>
            设置食谱日期
          </caption>
          <tbody>
            <tr>
              <td
                v-for="(item,index) in afterWeek"
                :key="index"
              >{{ item }}</td>
            </tr>
            <tr>
              <td
                v-for="(item,index) in afterMealTypeVal"
                :key="index"
              >{{ item }}</td>
            </tr>
            <tr>
              <td
                v-for="(item,index) in afterWeek"
                :key="index"
              >
                <a-checkbox
                  :checked="afterWeekChecked.find(i => i ===item)? true:false"
                  :disabled="state==='detail'"
                  @change="handleWeekCheck($event,item)"
                />
              </td>
            </tr>
          </tbody>
        </table>
        <table
          v-if="afterWeekCheckedCopy.length!==0"
          class="table"
        >
          <caption>
            设置就餐人数
          </caption>
          <tbody>
            <div style="text-align: left">在读人数：{{ totalPeople }}人</div>
            <tr>
              <td>星期</td>
              <td
                v-for="(item,index) in afterWeekChecked"
                :index="index"
              >
                {{ getWeekName(item) }}
              </td>
            </tr>
            <tr>
              <td>人数</td>
              <td
                v-for="(item,index) in afterWeekChecked"
                :key="index"
              >
                <a-input
                  v-model="form.planDayRecipesList.find(i => i.date === item).number"
                  :disabled="state==='detail'"
                  style="width: 60px;text-align: center;"
                  @change="handleKeepSync"
                />
              </td>
            </tr>
          </tbody>
          <div style="text-align: left">
            <a-checkbox
              v-model="isSync"
              :disabled="state==='detail'"
              style="width: 500px;padding-top: 10px;"
            >
              输入第一天的就餐人数时，其他填的人数与第一天同步
            </a-checkbox>
          </div>
        </table>
        <div class="btn">
          <a-button
            type="primary"
            @click="handleClickNext"
          >下一步(自定义食谱)</a-button>
        </div>
      </a-card>
    </a-card>
    <a-card v-else>
      <template
        slot="title"
        class="ant-card-actions"
      >
        <a-form-model
          :model="form"
          layout="inline"
          @submit.native.prevent
        >
          <a-form-model-item label="计划食谱名称">
            {{ form.planName }}
          </a-form-model-item>
          <a-form-model-item label="食谱日期:">
            {{ form.planRange }}
          </a-form-model-item>
        </a-form-model>
      </template>
      <div style="display: flex">
        <a-card
          style="flex: 4;margin-right: 10px;"
          title="具体安排"
        >
          <a-tabs
            v-model="curTab"
            style="overflow: visible !important;"
            type="card"
          >
            <a-tab-pane
              v-for="(item,index) in afterWeekChecked"
              :key="index"
              :tab="getWeekName(item)"
            >
              <table
                class="table"
                style="table-layout: auto"
              >
                <thead>
                  <tr>
                    <th>餐次</th>
                    <th>菜名</th>
                    <th>食物名</th>
                    <th>数量(人均量:克)</th>
                  </tr>
                </thead>
                <tbody>
                  <!--      给每个带餐次的设置背景颜色，并且一黑一白，         -->
                  <!--                :style="{background:item.name01 ?'#f5f5f5':'white'}"-->
                  <tr
                    v-for="(item, itemIndex) in tableData"
                    :key="itemIndex"
                    style="background: white"
                  >
                    <td
                      v-if="item.name01 || item.name01===0"
                      :rowspan="item.rowspan1"
                    >
                      <div style="text-align: center;margin: 5px;">{{ canCiName[item.name01] }}</div>
                      <a-button
                        v-if="state!=='detail'"
                        @click="handleAddRecipes(item.name01)"
                      >添加食谱
                      </a-button>
                    </td>
                    <!--  html标签生成的比数据更新的快,所以要加个v-if-->
                    <td
                      v-if="item.name02"
                      :rowspan="item.rowspan2"
                      style="width: 35%"
                    >
                      <!--一天中的食谱可以一样-->
                      <a-input
                        v-model="form.planDayRecipesList[curTab].planDayRecipesDetails.find(i => i.type === item.mealTypeVal).recipesList.find(i => i.recipesId === item.curRecipesId).recipesName"
                        :disabled="state==='detail'"
                        allowClear
                        style="width: 90%"
                        @change="handleCookBookChange(item.mealTypeVal,item.curRecipesId,$event)"
                        @click="current=itemIndex;rawRecipesId=item.curRecipesId;"
                        @dblclick="current=''"
                      />
                      <SelectCookBook
                        v-show="current===itemIndex"
                        :is-change-cook-book="isChangeCookBook"
                        :recipe-name="form.planDayRecipesList[curTab].planDayRecipesDetails.find(i => i.type === item.mealTypeVal).recipesList.find(i => i.recipesId === item.curRecipesId).recipesName"
                        @update:recipes="handleChangeRecipes(item.mealTypeVal,item.curRecipesId,arguments);current=''"
                      />
                      <div class="bottom_btn">
                        <a-button
                          :disabled="state==='detail'"
                          size="small"
                          @click="handleDeleteRecipes(item.mealTypeVal,item.curRecipesId)"
                        >
                          移除食谱
                        </a-button>
                        <a-button
                          :disabled="state==='detail'"
                          size="small"
                          @click="handleAddFood(item.mealTypeVal,item.curRecipesId)"
                        >
                          添加食物
                        </a-button>
                        <a-button
                          :disabled="state==='detail'"
                          size="small"
                          type="primary"
                          @click="handleSubmitRecipe(item.mealTypeVal,item.curRecipesId,item.curAbbreviation)"
                        >
                          保存食谱
                        </a-button>
                      </div>
                    </td>
                    <td style="width: 35%">
                      <a-input
                        v-model="item.foodName"
                        :disabled="state==='detail'"
                        allowClear
                        style="width: 80%"
                        @click="rawFoodId=item.detail.id;currentFood = itemIndex"
                        @dblclick="currentFood=undefined"
                      />
                      <!--气泡卡片-->
                      <a-popover
                        v-if="JSON.stringify(item.detail)!=='{}'"
                        placement="right"
                      >
                        <template slot="content">
                          <p>能量：{{ item.detail.heat }}</p>
                          <p>蛋白质：{{ item.detail.protein }}</p>
                          <p>碳水化合物：{{ item.detail.carbohydrate }}</p>
                          <p>脂肪：{{ item.detail.fat }}</p>
                          <p>钙：{{ item.detail.calcium }}</p>
                          <p>铁：{{ item.detail.iron }}</p>
                          <p>锌：{{ item.detail.zinc }}</p>
                          <p>维生素A：{{ item.detail.vitA }}</p>
                          <p>维生素B1：{{ item.detail.vitB1 }}</p>
                          <p>维生素B2：{{ item.detail.vitB2 }}</p>
                          <p>维生素C：{{ item.detail.vitC }}</p>
                        </template>
                        <a-icon
                          style="padding-left: 10px;height: 20px;"
                          type="exclamation-circle"
                        />
                      </a-popover>
                      <SelectTable
                        v-show="currentFood!==undefined && currentFood===itemIndex"
                        :type-id="curTypeId"
                        :queryText="item.foodName"
                        @update:foodMaterialsId="handleUpdateFoodMaterialsId(item.mealTypeVal,item.curRecipesId,arguments,item)"
                      />
                      <div class="bottom_btn">
                        <a-button
                          :disabled="state==='detail'||form.planDayRecipesList[curTab].planDayRecipesDetails.find(i => i.type === item.mealTypeVal).recipesList.find(i => i.recipesId === item.curRecipesId).recipesDetailsList.length===1"
                          size="small"
                          @click="rawFoodId=item.detail.id;handleDelFood(item.mealTypeVal,item.curRecipesId);"
                        >
                          移除食物
                        </a-button>
                        <a-button
                          :disabled="state==='detail'"
                          size="small"
                          @click="currentFood = itemIndex;rawFoodId=item.detail.id ;rawFoodId=item.detail.id;curTypeId=item.detail.foodMaterialsTypeId"
                        >
                          同类替换
                        </a-button>
                      </div>
                    </td>
                    <td>
                      <a-input-number
                        v-model="form.planDayRecipesList[curTab].planDayRecipesDetails.find(i => i.type === item.mealTypeVal).recipesList.find(i => i.recipesId === item.curRecipesId).recipesDetailsList.find(i =>i.detail.id === item.detail.id).weight"
                        :disabled="state==='detail'"
                        step="0.1"
                        style="width: 90%"
                      />
                    </td>
                  </tr>
                </tbody>
              </table>
            </a-tab-pane>
          </a-tabs>
        </a-card>
        <a-card
          :headStyle="{padding:'0 10px'}"
          style="flex: 2"
        >
          <template
            slot="title"
            style="padding: 0"
          >
            <div style="display: flex;justify-content: space-between">
              <div />
              <a-radio-button value="nutrition">
                营养分析
              </a-radio-button>
            </div>
          </template>
          <div style="padding: 5px 0">
            当日营养分析
          </div>
          <table class="table">
            <thead>
              <th style="border: 1px solid rgb(221, 221, 221);">营养</th>
              <th style="border: 1px solid rgb(221, 221, 221);">在园实给</th>
              <th style="border: 1px solid rgb(221, 221, 221);">在园标准</th>
              <th style="border: 1px solid rgb(221, 221, 221);">在园实给%</th>
              <th style="border: 1px solid rgb(221, 221, 221);">评分</th>
            </thead>
            <tbody>
              <tr>
                <td>能量</td>
                <td>{{ _.round(form.planDayRecipesList[curTab].nutritionalAnalysisDto.heat, 2) }}</td>
                <td>982.11</td>
                <td>{{ _.round(form.planDayRecipesList[curTab].nutritionalAnalysisDto.heat / 982.11 * 100, 2) }}</td>
                <td>
                  <span v-if="_.round(form.planDayRecipesList[curTab].nutritionalAnalysisDto.heat / 982.11 * 100, 2) < 80">低</span>
                  <span v-if="_.round(form.planDayRecipesList[curTab].nutritionalAnalysisDto.heat / 982.11 * 100, 2) > 120">高</span>
                  <span v-if="_.round(form.planDayRecipesList[curTab].nutritionalAnalysisDto.heat / 982.11 * 100, 2) > 80 && _.round(form.planDayRecipesList[curTab].nutritionalAnalysisDto.heat / 982.11 * 100, 2) < 120">合格</span>
                </td>
              </tr>
              <tr>
                <td>蛋白质</td>
                <td>{{ _.round(form.planDayRecipesList[curTab].nutritionalAnalysisDto.protein, 2) }}</td>
                <td>33.29</td>
                <td>{{ _.round(form.planDayRecipesList[curTab].nutritionalAnalysisDto.protein / 33.29 * 100, 2) }}</td>
                <td>
                  <span v-if="_.round(form.planDayRecipesList[curTab].nutritionalAnalysisDto.protein / 33.29 * 100, 2) < 80">低</span>
                  <span v-if="_.round(form.planDayRecipesList[curTab].nutritionalAnalysisDto.protein / 33.29 * 100, 2) > 120">高</span>
                  <span v-if="_.round(form.planDayRecipesList[curTab].nutritionalAnalysisDto.protein / 33.29 * 100, 2) > 80 && _.round(form.planDayRecipesList[curTab].nutritionalAnalysisDto.protein / 33.29 * 100, 2) < 120">合格</span>
                </td>
              </tr>
              <tr>
                <td>碳水化合物</td>
                <td>{{ _.round(form.planDayRecipesList[curTab].nutritionalAnalysisDto.carbohydrate, 2) }}</td>
                <td>138.58</td>
                <td>{{ _.round(form.planDayRecipesList[curTab].nutritionalAnalysisDto.carbohydrate / 138.58 * 100, 2) }}
                </td>
                <td>
                  <span v-if="_.round(form.planDayRecipesList[curTab].nutritionalAnalysisDto.carbohydrate / 138.58 * 100, 2) < 80">低</span>
                  <span v-if="_.round(form.planDayRecipesList[curTab].nutritionalAnalysisDto.carbohydrate / 138.58 * 100, 2) > 120">高</span>
                  <span v-if="_.round(form.planDayRecipesList[curTab].nutritionalAnalysisDto.carbohydrate / 138.58 * 100, 2) > 80 && _.round(form.planDayRecipesList[curTab].nutritionalAnalysisDto.carbohydrate / 138.58 * 100, 2) < 120">合格</span>
                </td>
              </tr>
              <tr>
                <td>脂肪</td>
                <td>{{ _.round(form.planDayRecipesList[curTab].nutritionalAnalysisDto.fat, 2) }}</td>
                <td>32.74</td>
                <td>{{ _.round(form.planDayRecipesList[curTab].nutritionalAnalysisDto.fat / 32.74 * 100, 2) }}</td>
                <td>
                  <span v-if="_.round(form.planDayRecipesList[curTab].nutritionalAnalysisDto.fat / 32.74 * 100, 2) < 80">低</span>
                  <span v-if="_.round(form.planDayRecipesList[curTab].nutritionalAnalysisDto.fat / 32.74 * 100, 2) > 120">高</span>
                  <span v-if="_.round(form.planDayRecipesList[curTab].nutritionalAnalysisDto.fat / 32.74 * 100, 2) > 80 && _.round(form.planDayRecipesList[curTab].nutritionalAnalysisDto.fat / 32.74 * 100, 2) < 120">合格</span>
                </td>
              </tr>
            </tbody>
          </table>
          <div style="width:200px;padding: 5px 0">
            一周日均营养分析
          </div>
          <table class="table">
            <thead>
              <tr>
                <th style="border: 1px solid rgb(221, 221, 221);">营养</th>
                <th style="border: 1px solid rgb(221, 221, 221);">在园实给</th>
                <th style="border: 1px solid rgb(221, 221, 221);">在园标准</th>
                <th style="border: 1px solid rgb(221, 221, 221);">在园实给%</th>
                <th style="border: 1px solid rgb(221, 221, 221);">评分</th>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td>能量</td>
                <td>
                  {{ _.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.heat, 0) / afterWeekChecked.length, 2)
                  }}
                </td>
                <td>982.11</td>
                <td>
                  {{ _.round(_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.heat, 0) / afterWeekChecked.length, 2) / 982.11 * 100, 2)
                  }}
                </td>
                <td>
                  <span v-if="_.round(_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.heat, 0) / afterWeekChecked.length, 2) / 982.11 * 100, 2) < 80">低</span>
                  <span v-if="_.round(_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.heat, 0) / afterWeekChecked.length, 2) / 982.11 * 100, 2) > 120">高</span>
                  <span v-if="_.round(_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.heat, 0) / afterWeekChecked.length, 2) / 982.11 * 100, 2) > 80 && _.round(_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.heat, 0) / afterWeekChecked.length, 2) / 982.11 * 100, 2) < 120">合格</span>
                </td>
              </tr>
              <tr>
                <td>蛋白质</td>
                <td>
                  {{ _.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.protein, 0) / afterWeekChecked.length, 2)
                  }}
                </td>
                <td>33.29</td>
                <td>
                  {{ _.round(_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.protein, 0) / afterWeekChecked.length, 2) / 33.29 * 100, 2)
                  }}
                </td>
                <td>
                  <span v-if="_.round(_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.protein, 0) / afterWeekChecked.length, 2) / 33.29 * 100, 2) < 80">低</span>
                  <span v-if="_.round(_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.protein, 0) / afterWeekChecked.length, 2) / 33.29 * 100, 2) > 120">高</span>
                  <span v-if="_.round(_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.protein, 0) / afterWeekChecked.length, 2) / 33.29 * 100, 2) > 80 && _.round(_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.protein, 0) / afterWeekChecked.length, 2) / 33.29 * 100, 2) < 120">合格</span>
                </td>
              </tr>
              <tr>
                <td>碳水化合物</td>
                <td>
                  {{ _.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.carbohydrate, 0) / afterWeekChecked.length, 2)
                  }}
                </td>
                <td>138.58</td>
                <td>
                  {{ _.round(_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.carbohydrate, 0) / afterWeekChecked.length, 2) / 138.58 * 100, 2)
                  }}
                </td>
                <td>
                  <span v-if="_.round(_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.carbohydrate, 0) / afterWeekChecked.length, 2) / 138.58 * 100, 2) < 80">低</span>
                  <span v-if="_.round(_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.carbohydrate, 0) / afterWeekChecked.length, 2) / 138.58 * 100, 2) > 120">高</span>
                  <span v-if="_.round(_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.carbohydrate, 0) / afterWeekChecked.length, 2) / 138.58 * 100, 2) > 80 && _.round(_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.carbohydrate, 0) / afterWeekChecked.length, 2) / 138.58 * 100, 2) < 120">合格</span>
                </td>
              </tr>
              <tr>
                <td>脂肪</td>
                <td>
                  {{ _.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.fat, 0) / afterWeekChecked.length, 2)
                  }}
                </td>
                <td>32.74</td>
                <td>
                  {{ _.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.fat, 0) / afterWeekChecked.length / 32.74 * 100, 2)
                  }}
                </td>
                <td>
                  <span v-if="_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.fat, 0) / afterWeekChecked.length / 32.74 * 100, 2) < 80">低</span>
                  <span v-if="_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.fat, 0) / afterWeekChecked.length / 32.74 * 100, 2) > 120">高</span>
                  <span v-if="_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.fat, 0) / afterWeekChecked.length / 32.74 * 100, 2) > 80 && _.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.fat, 0) / afterWeekChecked.length / 32.74 * 100, 2) < 120">合格</span>
                </td>
              </tr>
              <tr>
                <td>钙</td>
                <td>
                  {{ _.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.calcium, 0) / afterWeekChecked.length, 2)
                  }}
                </td>
                <td>486.32</td>
                <td>
                  {{ _.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.calcium, 0) / afterWeekChecked.length / 486.32 * 100, 2)
                  }}
                </td>
                <td>
                  <span v-if="_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.calcium, 0) / afterWeekChecked.length / 486.32 * 100, 2) < 80">低</span>
                  <span v-if="_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.calcium, 0) / afterWeekChecked.length / 486.32 * 100, 2) > 120">高</span>
                  <span v-if="_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.calcium, 0) / afterWeekChecked.length / 486.32 * 100, 2) > 80 && _.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.calcium, 0) / afterWeekChecked.length / 486.32 * 100, 2) < 120">合格</span>
                </td>
              </tr>
              <tr>
                <td>铁</td>
                <td>
                  {{ _.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.iron, 0) / afterWeekChecked.length, 2)
                  }}
                </td>
                <td>8.4</td>
                <td>
                  {{ _.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.iron, 0) / afterWeekChecked.length / 8.4 * 100, 2)
                  }}
                </td>
                <td>
                  <span v-if="_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.iron, 0) / afterWeekChecked.length / 8.4 * 100, 2) < 80">低</span>
                  <span v-if="_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.iron, 0) / afterWeekChecked.length / 8.4 * 100, 2) > 120">高</span>
                  <span v-if="_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.iron, 0) / afterWeekChecked.length / 8.4 * 100, 2) > 80 && _.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.iron, 0) / afterWeekChecked.length / 8.4 * 100, 2) < 120">合格</span>
                </td>
              </tr>
              <tr>
                <td>锌</td>
                <td>
                  {{ _.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.zinc, 0) / afterWeekChecked.length, 2)
                  }}
                </td>
                <td>7.29</td>
                <td>
                  {{ _.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.zinc, 0) / afterWeekChecked.length / 7.29 * 100, 2)
                  }}
                </td>
                <td>
                  <span v-if="_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.zinc, 0) / afterWeekChecked.length / 7.29 * 100, 2) < 80">低</span>
                  <span v-if="_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.zinc, 0) / afterWeekChecked.length / 7.29 * 100, 2) > 120">高</span>
                  <span v-if="_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.zinc, 0) / afterWeekChecked.length / 7.29 * 100, 2) > 80 && _.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.zinc, 0) / afterWeekChecked.length / 7.29 * 100, 2) < 120">合格</span>
                </td>
              </tr>
              <tr>
                <td>维生素A</td>
                <td>
                  {{ _.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.vitA, 0) / afterWeekChecked.length, 2)
                  }}
                </td>
                <td>383.16</td>
                <td>
                  {{ _.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.vitA, 0) / afterWeekChecked.length / 383.16 * 100, 2)
                  }}
                </td>
                <td>
                  <span v-if="_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.vitA, 0) / afterWeekChecked.length / 383.16 * 100, 2) < 80">低</span>
                  <span v-if="_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.vitA, 0) / afterWeekChecked.length / 383.16 * 100, 2) > 120">高</span>
                  <span v-if="_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.vitA, 0) / afterWeekChecked.length / 383.16 * 100, 2) > 80 && _.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.vitA, 0) / afterWeekChecked.length / 383.16 * 100, 2) < 120">合格</span>
                </td>
              </tr>
              <tr>
                <td>维生素B1</td>
                <td>
                  {{ _.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.vitB1, 0) / afterWeekChecked.length, 2)
                  }}
                </td>
                <td>0.46</td>
                <td>
                  {{ _.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.vitB1, 0) / afterWeekChecked.length / 0.46 * 100, 2)
                  }}
                </td>
                <td>
                  <span v-if="_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.vitB1, 0) / afterWeekChecked.length / 0.46 * 100, 2) < 80">低</span>
                  <span v-if="_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.vitB1, 0) / afterWeekChecked.length / 0.46 * 100, 2) > 120">高</span>
                  <span v-if="_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.vitB1, 0) / afterWeekChecked.length / 0.46 * 100, 2) > 80 && _.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.vitB1, 0) / afterWeekChecked.length / 0.46 * 100, 2) < 120">合格</span>
                </td>
              </tr>
              <tr>
                <td>维生素B2</td>
                <td>
                  {{ _.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.vitB2, 0) / afterWeekChecked.length, 2)
                  }}
                </td>
                <td>0.46</td>
                <td>
                  {{ _.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.vitB2, 0) / afterWeekChecked.length / 45.32 * 100, 2)
                  }}
                </td>
                <td>
                  <span v-if="_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.vitB2, 0) / afterWeekChecked.length / 45.32 * 100, 2) < 80">低</span>
                  <span v-if="_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.vitB2, 0) / afterWeekChecked.length / 45.32 * 100, 2) > 120">高</span>
                  <span v-if="_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.vitB2, 0) / afterWeekChecked.length / 45.32 * 100, 2) > 80 && _.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.vitB2, 0) / afterWeekChecked.length / 45.32 * 100, 2) < 120">合格</span>
                </td>
              </tr>
              <tr>
                <td>维生素C</td>
                <td>
                  {{ _.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.vitC, 0) / afterWeekChecked.length)
                  }}
                </td>
                <td>45.32</td>
                <td>
                  {{ _.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.vitC, 0) / afterWeekChecked.length / 45.32 * 100, 2)
                  }}
                </td>
                <td>
                  <span v-if="_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.vitC, 0) / afterWeekChecked.length / 45.32 * 100, 2) < 80">低</span>
                  <span v-if="_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.vitC, 0) / afterWeekChecked.length / 45.32 * 100, 2) > 120">高</span>
                  <span v-if="_.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.vitC, 0) / afterWeekChecked.length / 45.32 * 100, 2) > 80 && _.round(form.planDayRecipesList.reduce((pre, cur) => pre + cur.nutritionalAnalysisDto.vitC, 0) / afterWeekChecked.length / 45.32 * 100, 2) < 120">合格</span>
                </td>
              </tr>
            </tbody>
          </table>
        </a-card>
      </div>
      <div class="btn">
        <a-button @click="curStep=0">上一步</a-button>
        <a-button
          v-if="state!=='detail'"
          @click="handleSubmit"
        >提交</a-button>
      </div>
    </a-card>
  </div>
</template>

<script>
import dayjs from "dayjs";
import { childrenPage } from "@/api/modular/children/childManage";
import {
  addCookBookStore,
  cookBookStoreList,
  detailCookBookStore,
  editCookBookStore
} from "@/api/modular/cookBook/cookBookManage";
import { addDietPlanApi, dietPlanDetailApi } from "@/api/modular/dietPlan";
import { getUuid } from "@/utils/util";
import moment from "moment";
import SelectCookBook from "@/views/dietPlan/SelectCookBook";
import SelectTable from "@/views/cookbook/SelectTable";

const weeks = ["日", "一", "二", "三", "四", "五", "六"];
export default {
  components: { SelectCookBook, SelectTable },
  props: ["state", "baseInfo"],
  data() {
    return {
      rawRecipesId: undefined,
      current: undefined,
      currentFood: undefined,
      curTypeId: undefined,
      isNewRecipe: false,
      isChangeCookBook: undefined,
      rawFoodId: undefined,
      canCiName: ["早餐", "早点", "午餐", "午点", "晚餐", "晚点"],
      curStep: 0,
      endTime: undefined,
      form: {
        id: getUuid(),
        planName: "",
        planRange: "",
        starTime: undefined,
        endTime: undefined,
        planDayRecipesList: []
      },
      tableData: [],
      afterWeek: [], // 格式化日期数组
      afterMealTypeVal: [], // 转换成星期x的格式数组
      afterWeekChecked: [], // 选中的日期数组
      showConfirmSelectDateDialog: false,// 日期选择提醒对话框
      firstDayNameOfWeek: "",
      isSync: true,
      totalPeople: 0,
      curTab: 0,
      curInput: 0,
      selectOptions: []
    };
  },
  created() {
    this.dealState();
    this.getInitData();
    this.getOptionsData();
  },
  computed: {
    afterWeekCheckedCopy() {
      // 如果想监听一个数组，然后每次这个数组每次改变，对他进行排序，必须先通过计算属性得到具体的值，直接用监听器会陷入死循环
      return JSON.parse(JSON.stringify(this.afterWeekChecked.sort((a, b) => new Date(a).getTime() - new Date(b).getTime())));
    }
  },
  watch: {
    // 这里应该是检测日期数组
    afterWeekCheckedCopy(newVal, oldVal) {
      if (newVal.length === 0) return;
      // 默认每次切换后显示第一个
      this.curTab = 0;
      // 详情和修改第一次渲染数据
      if (this.state !== "add" && oldVal.length === 0) return;
      if (!oldVal.length) {
        // 1.新增时，一开始选中之前没有数据结构
        newVal.forEach(item => {
          this.form.planDayRecipesList.push({
            id: getUuid(),
            planWeekRecipesId: getUuid(),
            date: item,
            dateStr: this.afterMealTypeVal[this.afterWeek.findIndex(i => i === item)],
            number: this.totalPeople,
            planDayRecipesDetails: [
              {
                type: 0,
                recipesList: [{
                  recipesName: "",
                  recipesId: getUuid(),
                  recipesDetailsList: [{ id: getUuid(), foodName: "", detail: {}, weight: undefined }]
                }]
              },
              {
                type: 1,
                recipesList: [{
                  recipesName: "",
                  recipesId: getUuid(),
                  recipesDetailsList: [{ id: getUuid(), foodName: "", detail: {}, weight: undefined }]
                }]
              },
              {
                type: 2,
                recipesList: [{
                  recipesName: "",
                  recipesId: getUuid(),
                  recipesDetailsList: [{ id: getUuid(), foodName: "", detail: {}, weight: undefined }]
                }]
              },
              {
                type: 3,
                recipesList: [{
                  recipesName: "",
                  recipesId: getUuid(),
                  recipesDetailsList: [{ id: getUuid(), foodName: "", detail: {}, weight: undefined }]
                }]
              },
              {
                type: 4,
                recipesList: [{
                  recipesName: "",
                  recipesId: getUuid(),
                  recipesDetailsList: [{ id: getUuid(), foodName: "", detail: {}, weight: undefined }]
                }]
              },
              {
                type: 5,
                recipesList: [{
                  recipesName: "",
                  recipesId: getUuid(),
                  recipesDetailsList: [{ id: getUuid(), foodName: "", detail: {}, weight: undefined }]
                }]
              }
            ],
            nutritionalAnalysisDto: {
              heat: 0,
              protein: 0,
              fat: 0,
              carbohydrate: 0,
              calcium: 0,
              iron: 0,
              zinc: 0,
              vitA: 0,
              vitB1: 0,
              vitB2: 0,
              vitC: 0
            }
          });
        });
      } else {
        // 2.找出差异，新增添加，减少删除
        // console.log(this._.difference(['星期一', '星期二', '星期三', '星期四', '星期五'],['星期一', '星期二', '星期三', '星期四'])) 这个difference必须多的在前面
        // console.log(newVal,'new',oldVal,'old')
        if (newVal.length >= oldVal.length) {
          const diffArr = this._.difference(newVal, oldVal);
          // 如果没有一个
          const isAllDiff = !oldVal.some(i => diffArr.includes(i));
          if (isAllDiff) {
            this.form.planDayRecipesList = [];
            newVal.forEach(item => {
              this.form.planDayRecipesList.push({
                id: getUuid(),
                planWeekRecipesId: getUuid(),
                date: item,
                dateStr: this.afterMealTypeVal[this.afterWeek.findIndex(i => i === item)],
                number: this.totalPeople,
                planDayRecipesDetails: [
                  {
                    type: 0,
                    recipesList: [{
                      recipesName: "",
                      recipesId: getUuid(),
                      recipesDetailsList: [{ id: getUuid(), foodName: "", detail: {}, weight: undefined }]
                    }]
                  },
                  {
                    type: 1,
                    recipesList: [{
                      recipesName: "",
                      recipesId: getUuid(),
                      recipesDetailsList: [{ id: getUuid(), foodName: "", detail: {}, weight: undefined }]
                    }]
                  },
                  {
                    type: 2,
                    recipesList: [{
                      recipesName: "",
                      recipesId: getUuid(),
                      recipesDetailsList: [{ id: getUuid(), foodName: "", detail: {}, weight: undefined }]
                    }]
                  },
                  {
                    type: 3,
                    recipesList: [{
                      recipesName: "",
                      recipesId: getUuid(),
                      recipesDetailsList: [{ id: getUuid(), foodName: "", detail: {}, weight: undefined }]
                    }]
                  },
                  {
                    type: 4,
                    recipesList: [{
                      recipesName: "",
                      recipesId: getUuid(),
                      recipesDetailsList: [{ id: getUuid(), foodName: "", detail: {}, weight: undefined }]
                    }]
                  },
                  {
                    type: 5,
                    recipesList: [{
                      recipesName: "",
                      recipesId: getUuid(),
                      recipesDetailsList: [{ id: getUuid(), foodName: "", detail: {}, weight: undefined }]
                    }]
                  }
                ],
                nutritionalAnalysisDto: {
                  heat: 0,
                  protein: 0,
                  fat: 0,
                  carbohydrate: 0,
                  calcium: 0,
                  iron: 0,
                  zinc: 0,
                  vitA: 0,
                  vitB1: 0,
                  vitB2: 0,
                  vitC: 0
                }
              });
            });
          } else {
            diffArr.forEach(item => {
              //2.1 新增了(位置还是不能变)
              this.form.planDayRecipesList.push({
                id: getUuid(),
                planWeekRecipesId: getUuid(),
                date: item,
                dateStr: "星期" + weeks[dayjs(item).day()],
                number: this.totalPeople,
                planDayRecipesDetails: [
                  {
                    type: 0,
                    recipesList: [{
                      recipesName: "",
                      recipesId: getUuid(),
                      recipesDetailsList: [{ id: getUuid(), foodName: "", detail: {}, weight: undefined }]
                    }]
                  },
                  {
                    type: 1,
                    recipesList: [{
                      recipesName: "",
                      recipesId: getUuid(),
                      recipesDetailsList: [{ id: getUuid(), foodName: "", detail: {}, weight: undefined }]
                    }]
                  },
                  {
                    type: 2,
                    recipesList: [{
                      recipesName: "",
                      recipesId: getUuid(),
                      recipesDetailsList: [{ id: getUuid(), foodName: "", detail: {}, weight: undefined }]
                    }]
                  },
                  {
                    type: 3,
                    recipesList: [{
                      recipesName: "",
                      recipesId: getUuid(),
                      recipesDetailsList: [{ id: getUuid(), foodName: "", detail: {}, weight: undefined }]
                    }]
                  },
                  {
                    type: 4,
                    recipesList: [{
                      recipesName: "",
                      recipesId: getUuid(),
                      recipesDetailsList: [{ id: getUuid(), foodName: "", detail: {}, weight: undefined }]
                    }]
                  },
                  {
                    type: 5,
                    recipesList: [{
                      recipesName: "",
                      recipesId: getUuid(),
                      recipesDetailsList: [{ id: getUuid(), foodName: "", detail: {}, weight: undefined }]
                    }]
                  }
                ],
                nutritionalAnalysisDto: {
                  heat: 0,
                  protein: 0,
                  fat: 0,
                  carbohydrate: 0,
                  calcium: 0,
                  iron: 0,
                  zinc: 0,
                  vitA: 0,
                  vitB1: 0,
                  vitB2: 0,
                  vitC: 0
                }
              });
            });
            this.form.planDayRecipesList = this.form.planDayRecipesList.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());
          }

        } else if (newVal.length < oldVal.length) {
          // 2.2删除了
          const diffArr = this._.difference(oldVal, newVal); // 每次的差异
          diffArr.forEach(i => this.form.planDayRecipesList = this.form.planDayRecipesList.filter(j => j.date !== i));
        }
      }
      // 获取食谱周期
      this.form.planRange = newVal[0] ? newVal.length > 1 ? newVal[0] + "至" + newVal[newVal.length - 1] : newVal[0] : null;
      this.handleFormData(this.form.planDayRecipesList[this.curTab].planDayRecipesDetails);
    },
    // 监听form改变tableData,这样其实开销有点大
    "form": {
      handler() {
        if (this.form.planDayRecipesList[this.curTab]) {
          this.handleFormData(this.form.planDayRecipesList[this.curTab].planDayRecipesDetails);
        }
      },
      deep: true
    },
    curTab() {
      this.handleFormData(this.form.planDayRecipesList[this.curTab].planDayRecipesDetails);
    }
  },
  methods: {
    getUuid,
    isCloseSelectBox(e) {
      if (e.target.className !== "ant-input") {
        this.current = "";
        this.currentFood = "";
      }
    },
    async dealState() {
      // 非新增页面时
      if (this.state !== "add") {
        this.form.id = this.baseInfo.id;
        this.form.planName = this.baseInfo.planName;
        this.form.planRange = this.baseInfo.planRange;
        this.form.starTime = moment(this.baseInfo.startTime);
        const { data: data } = await dietPlanDetailApi({ PlanWeekRecipesId: this.baseInfo.id });
        this.afterWeek = data.map(i => i.date).sort((a, b) => new Date(a).getTime() - new Date(b).getTime());
        this.afterMealTypeVal = data.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime()).map(i => i.dateStr);
        this.afterWeekChecked = data.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime()).map(i => i.date);
        this.form.planDayRecipesList = data;
        // 按餐次排序一下
        this.form.planDayRecipesList.forEach(i => i.planDayRecipesDetails.sort((a, b) => a.type - b.type));
        this.form.planDayRecipesList.forEach(i => i.planDayRecipesDetails.forEach(j => j.recipesList.forEach(k => k.id = this.getUuid())));
        // 获取菜谱详情
        this.form.planDayRecipesList.forEach(item => {
          item.planDayRecipesDetails.forEach(i => i.recipesList.forEach(async (j) => {
            const { data: data02 } = await detailCookBookStore({ recipesId: j.recipesId });
            const newArr = data02.map(i => {
              return {
                id: i.recipesId,
                foodName: i.foodMaterials.foodName,
                weight: i.weight,
                detail: i.foodMaterials
              };
            });
            j.recipesDetailsList = newArr;
          }));
        });
      }
    },
    handleClick(val) {
      this.curInput = val;
    },
    async handleSubmit() {
      // 是否有空
      let isHaveEmpty = false;
      this.form.planDayRecipesList.forEach(i => {
        i.planDayRecipesDetails.forEach(j => {
          j.recipesList.forEach(k => {
            k.recipesDetailsList.forEach(g => {
              if (!g.weight) {
                isHaveEmpty = true;
              }
              ;
            });
          });
        });
      });
      if (isHaveEmpty) return this.$message.warning(" 请先填写完整再提交！");
      // 整理食谱id
      this.form.planDayRecipesList.forEach(i => {
        i.planDayRecipesDetails.forEach(j => {
          j.recipesIdList = [];
          j.recipesList.forEach(k => j.recipesIdList.push(k.recipesId));
        });
      });
      const resp = await addDietPlanApi(this.form);
      resp.code === 200 ? this.$emit("change-to-table") : this.$message.warning(resp.message);
    },
    async getOptionsData() {
      const { data: data } = await cookBookStoreList({ pageNo: 1, pageSize: 1000 });
      this.selectOptions = data.rows.map(i => {
          return { value: i.recipesId, label: i.recipesName };
        }
      );
    },
    async getInitData() {
      // 获取在园总人数
      const resp = await childrenPage({ state: 2 });
      this.totalPeople = resp.data.totalRows;
    },
    handleDateChange({ _d }) {
      // 清空之前的
      this.afterWeek = [];
      this.afterMealTypeVal = [];
      const curDate = dayjs(_d);
      // 获取之后的七天的日期数据
      for (let i = 0; i < 7; i++) {
        const cur = curDate.add(i, "day");
        this.afterWeek.push(cur.format("YYYY-MM-DD"));
        this.afterMealTypeVal.push("星期" + weeks[cur.day()]);
      }
      // 判断选的是不是周一
      this.firstDayNameOfWeek = "星期" + weeks[dayjs(_d).day()];
      if (this.firstDayNameOfWeek !== "星期一") return this.showConfirmSelectDateDialog = true;
      // 如果选择中的日期为周一则，下面默认选中星期一到星期五，否则不选中
      this.afterWeekChecked = this.afterWeek.slice(0, 5);
    },
    handleWeekCheck({ target }, dateString) {
      if (target.checked) {
        this.afterWeekChecked.push(dateString);
      } else {
        this.afterWeekChecked = this.afterWeekChecked.filter(i => i !== dateString);
      }
    },
    handleKeepSync() {
      if (this.isSync) {
        this.form.planDayRecipesList.forEach(i => i.number = this.form.planDayRecipesList[0].number);
      }
    },
    handleClickNext() {
      if (!this.form.planName) return this.$message.warning(" 食谱名称不能为空！");
      this.curStep = 1;
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    handleAddRecipes(type) {
      this.form.planDayRecipesList[this.curTab].planDayRecipesDetails.find(i => i.type === type).recipesList.push({
        recipesId: getUuid(),
        value: "",
        recipesDetailsList: [{ id: getUuid(), foodName: "", detail: {}, weight: undefined }]
      });
    },
    handleDeleteRecipes(mealTypeVal, recipeArrId) {
      let curRecipesList = this.form.planDayRecipesList[this.curTab].planDayRecipesDetails.find(i => i.type === mealTypeVal).recipesList;
      // 这样赋值不行不知道为什么
      // curRecipesList = []
      // console.log(this.form,'1')
      if (curRecipesList.length === 1) {
        this.form.planDayRecipesList[this.curTab].planDayRecipesDetails.find(i => i.type === mealTypeVal).recipesList = [{
          recipesName: "",
          recipesId: this.getUuid(),
          recipesDetailsList: [{ id: getUuid(), foodName: "", detail: {}, weight: undefined }]
        }];
      } else {
        this.form.planDayRecipesList[this.curTab].planDayRecipesDetails.find(i => i.type === mealTypeVal).recipesList = this.form.planDayRecipesList[this.curTab].planDayRecipesDetails.find(i => i.type === mealTypeVal).recipesList.filter(i => i.recipesId !== recipeArrId);
      }
    },
    handleCookBookChange(mealTypeVal, curRecipesId, e) {
      this.form.planDayRecipesList[this.curTab].planDayRecipesDetails.find(i => i.type === mealTypeVal).recipesList.find(i => i.recipesId === curRecipesId).recipesName = e.target.value;
      this.isNewRecipe = true;
      this.current = undefined;
    },
    async handleSubmitRecipe(mealTypeVal, recipesId) {
      // 1.可以通过食谱详情，通过传id，找得到就有，反之没有
      const { data: data } = await detailCookBookStore({ recipesId });
      let isEmpty = false;
      this.form.planDayRecipesList[this.curTab].planDayRecipesDetails.find(i => i.type === mealTypeVal).recipesList.find(i => i.recipesId === recipesId).recipesDetailsList.forEach(i => {
        if (!i.weight) isEmpty = true;
      });
      if (isEmpty) return this.$message.warning(" 请先填写完整再提交！");
      // // 2.存在修改,不存在新增
      if (data.length !== 0) { // 修改

        const { data: newRecipesId } = await editCookBookStore(
          {
            id: recipesId, // 食谱id
            abbreviation: this.form.planDayRecipesList[this.curTab].planDayRecipesDetails.find(i => i.type === mealTypeVal).recipesList.find(i => i.recipesId === recipesId).abbreviation,
            recipeName: this.form.planDayRecipesList[this.curTab].planDayRecipesDetails.find(i => i.type === mealTypeVal).recipesList.find(i => i.recipesId === recipesId).recipesName,
            recipesDetailsList: this.form.planDayRecipesList[this.curTab].planDayRecipesDetails.find(i => i.type === mealTypeVal).recipesList.find(i => i.recipesId === recipesId).recipesDetailsList.map(i => {
              return {
                foodMaterialsId: i.detail.id, // 食物id
                weight: i.weight,
                foodName: i.foodName,
                recipesId
              };
            })
          }
        );

        // 修改之后所有相关联数据都要改变
        this.form.planDayRecipesList.forEach(i => {
          i.planDayRecipesDetails.forEach(j => {
            j.recipesList.forEach(async (k) => {
              if (k.recipesId === recipesId) { // 将有修改的食谱更新
                const { data: data } = await detailCookBookStore({ recipesId: newRecipesId });
                const newArr = data.map(i => {
                  return {
                    id: i.recipesId,
                    foodName: i.foodMaterials.foodName,
                    weight: i.weight,
                    detail: i.foodMaterials
                  };
                });

                k.recipesId = newRecipesId;
                k.recipesDetailsList = newArr;
                const nutritionalArr = ["calcium", "carbohydrate", "fat", "heat", "iron", "protein", "vitA", "vitB1", "vitB2", "vitC", "zinc"];
                // 重新计算
                j.nutritionalAnalysisDto = {
                  heat: 0,
                  protein: 0,
                  fat: 0,
                  carbohydrate: 0,
                  calcium: 0,
                  iron: 0,
                  zinc: 0,
                  vitA: 0,
                  vitB1: 0,
                  vitB2: 0,
                  vitC: 0
                };

                i.planDayRecipesDetails.forEach(a => {
                  a.recipesList.forEach(b => {
                    b.recipesDetailsList.forEach(c => {
                      nutritionalArr.forEach((item) => {
                        const val = (c.detail[item] / 100) * c.weight;
                        i.nutritionalAnalysisDto[item] += val;
                      });
                    });
                  });
                });
              }
              ;
            });
          });
        });

      } else {
        await addCookBookStore({
          id: recipesId,
          abbreviation: "*",
          recipeName: this.form.planDayRecipesList[this.curTab].planDayRecipesDetails.find(i => i.type === mealTypeVal).recipesList.find(i => i.recipesId === recipesId).recipesName,
          recipesDetailsList: this.form.planDayRecipesList[this.curTab].planDayRecipesDetails.find(i => i.type === mealTypeVal).recipesList.find(i => i.recipesId === recipesId).recipesDetailsList.map(i => {
            return {
              id: getUuid(),
              recipesId,
              weight: i.weight,
              foodMaterialsId: i.id,
              foodName: i.foodName
            };
          })
        });
      }
      this.isChangeCookBook = getUuid();
    },
    handleUpdateFoodMaterialsId(name01, name02, args, item) {
      const curRecipesDetailsList = this.form.planDayRecipesList[this.curTab].planDayRecipesDetails.find(i => i.type === name01).recipesList.find(i => i.recipesId === name02).recipesDetailsList;
      if (curRecipesDetailsList.find(i => i.id === args[0])) {
        item.foodName = "";
        return this.$message.warning("食谱中已存在该食物！");
      }
      let curFood = undefined;
      curFood = curRecipesDetailsList.find(i => i.detail.id === this.rawFoodId);
      curFood.detail.id = args[0];
      curFood.foodName = args[1];
      this.currentFood = undefined;
      if (this.curTypeId) this.curTypeId = undefined;
    },
    async handleChangeRecipes(mealTypeVal, curRecipesId, args) {
      const { data: data } = await detailCookBookStore({ recipesId: args[0] });
      const newArr = data.map(i => {
        return {
          id: i.recipesId,
          foodName: i.foodMaterials.foodName,
          weight: i.weight,
          detail: i.foodMaterials
        };
      });
      const tempObj = this.form.planDayRecipesList[this.curTab].planDayRecipesDetails.find(i => i.type === mealTypeVal).recipesList.find(i => i.recipesId === this.rawRecipesId);
      tempObj.recipesId = args[0];
      tempObj.recipesName = args[1];
      tempObj.abbreviation = args[2];
      tempObj.recipesDetailsList = newArr;
      const nutritionalArr = ["calcium", "carbohydrate", "fat", "heat", "iron", "protein", "vitA", "vitB1", "vitB2", "vitC", "zinc"];
      // 每次更换选项时清空重新算一下
      this.form.planDayRecipesList[this.curTab].nutritionalAnalysisDto = {
        heat: 0,
        protein: 0,
        fat: 0,
        carbohydrate: 0,
        calcium: 0,
        iron: 0,
        zinc: 0,
        vitA: 0,
        vitB1: 0,
        vitB2: 0,
        vitC: 0
      };
      this.form.planDayRecipesList[this.curTab].planDayRecipesDetails.forEach(i => {
        if (i.recipesList[0].recipesId) {
          i.recipesList.forEach(j => {
            if (j.recipesDetailsList[0].foodName) {
              j.recipesDetailsList.forEach(k => {
                // 假设现在俩个菜 遍历两个菜,然后对每个菜进行累加
                nutritionalArr.forEach((item) => {
                  const val = (k.detail[item] / 100) * k.weight;
                  this.form.planDayRecipesList[this.curTab].nutritionalAnalysisDto[item] += val;
                });
              });
            }
          });
        }
      });
    },
    handleAddFood(name01, name02) {
      this.form.planDayRecipesList[this.curTab].planDayRecipesDetails.find(i => i.type === name01).recipesList.find(i => i.recipesId = name02).recipesDetailsList.push({
        id: getUuid(),
        foodName: "",
        weight: "",
        detail: {}
      });
    },
    handleDelFood(curMealTypeVal, curRecipesId) {
      const curFoodList = this.form.planDayRecipesList[this.curTab].planDayRecipesDetails.find(i => i.type === curMealTypeVal).recipesList.find(i => i.recipesId = curRecipesId).recipesDetailsList;
      if (curFoodList.length === 0) {
        this.form.planDayRecipesList[this.curTab].planDayRecipesDetails.find(i => i.type === curMealTypeVal).recipesList.find(i => i.recipesId = curRecipesId).recipesDetailsList = [{
          id: getUuid(),
          foodName: "",
          weight: "",
          detail: {}
        }];
      } else {
        const temp = this.form.planDayRecipesList[this.curTab].planDayRecipesDetails.find(i => i.type === curMealTypeVal).recipesList.find(i => i.recipesId = curRecipesId).recipesDetailsList.filter(i => i.detail.id !== this.rawFoodId);
        this.form.planDayRecipesList[this.curTab].planDayRecipesDetails.find(i => i.type === curMealTypeVal).recipesList.find(i => i.recipesId = curRecipesId).recipesDetailsList = temp;
      }
    },
    // handleLeave() {
    //   console.log("111111111111");
    // },
    handleFormData(data) {
      const newData = data.map((item) => {
        // 得到第一层的rowspan
        let rows = 0;
        item.recipesList.forEach((item2) => {
          rows += item2.recipesDetailsList.length;
        });
        item.rowspan = rows;
        return item;
      });
      var mydata = new Array();
      newData.forEach((projectItem) => {
        projectItem.recipesList.forEach((modelItem, modelIndex) => {
          modelItem.recipesDetailsList.forEach((taskItem, taskIndex) => {
            // 第一层的时候：grandfather 和 father都有 rowspan
            if (modelIndex === 0 && taskIndex === 0) {
              mydata.push({
                name01: projectItem.type,
                // 每个都复制一个避免无法查找 0.0
                mealTypeVal: projectItem.type,
                rowspan1: projectItem.rowspan,
                name02: modelItem.recipesId,
                curRecipesId: modelItem.recipesId,
                curRecipesName: modelItem.recipesName,
                rowspan2: modelItem.recipesDetailsList.length,
                ...taskItem
              });
              // 第二层的时候： 只有father 有 rowspan
            } else if (taskIndex === 0) {
              mydata.push({
                mealTypeVal: projectItem.type,
                rowspan2: modelItem.recipesDetailsList.length,
                name02: modelItem.recipesId,
                curRecipesName: modelItem.recipesName,
                curRecipesId: modelItem.recipesId,
                ...taskItem
              });
            } else {
              mydata.push({
                mealTypeVal: projectItem.type,
                curRecipesId: modelItem.recipesId,
                curRecipesName: modelItem.recipesName,
                ...taskItem
              });
            }
          });
        });
      });
      this.tableData = mydata;
    },
    getWeekName(val) {
      return "星期" + weeks[dayjs(val).day()];
    }
  }
};
</script>

<style lang="less" scoped>
.table {
  display: table;
  // 固定每个单元格的宽度
  table-layout: fixed;
  width: 100%;
  border-collapse: collapse;
  text-align: center;
  caption-side: top;


  caption {
    display: block;
    width: 200px;
    color: black;
    font-size: 20px;
  }

  tr {
    width: 100%;
    //display: flex;
  }

  td {
    padding: 10px 0;
    border: 1px solid rgb(221, 221, 221);
  }

  tbody {
    tr:nth-child(odd) {
      background: #f5f5f5;
    }
  }

  //div {
  //  text-align: left;
  //}
}

.bottom_btn {
  display: flex;
  justify-content: space-evenly;
  margin-top: 10px;
}

.btn {
  text-align: center;

  button {
    margin: 10px;
  }
}

.confirmDateDialog {
  .btn {
    width: 100px;
    margin: 10px;
  }
}
</style>